#include "workproces.h"

workProces::workProces(QObject *parent) : QObject(parent) {
  currentThread = new QThread();
  this->moveToThread(currentThread);
  runProc.moveToThread(currentThread);

  connect(&runProc, &QProcess::readyReadStandardOutput, this,
          &workProces::onReadData);
  connect(&runProc, &QProcess::readyReadStandardError, this,
          &workProces::onReadError);

  runProc.setReadChannel(QProcess::StandardOutput);

  currentThread->start();
  bStart = false;
}

workProces::~workProces() {
  if (currentThread->isRunning()) {
    currentThread->quit();
    while (true == currentThread->isRunning())
      ;
  }
  currentThread->deleteLater();
}
void workProces::setRunInfo(const QString &objName, const QString &jdk,
                            const QString &cmd, const QStringList &list) {
  if (0 != QString::compare(objName, this->objectName())) {
    return;
  }

  bStart = true;
  javaEnv = jdk;
  exeCmd = cmd;
  argList = list;

  QString sPath, javaBin, jrePath, jreClass, javaClass;

  javaBin = javaEnv + "/bin";
  jrePath = javaEnv + "/jre/bin";

  javaClass = javaEnv + "/lib/dt.jar";
  jreClass = javaEnv + "/lib/tools.jar";

  QStringList sysPathList = QProcessEnvironment::systemEnvironment()
                                .value(QString("Path"))
                                .split(";");

  QStringList filterList = sysPathList.filter("jdk");
  for (int index = 0; index < filterList.count(); index++) {
    sysPathList.removeOne(filterList[index]);
  }

  sysPathList.insert(
      0, QDir::toNativeSeparators(QCoreApplication::applicationDirPath()));

  /* jdk运行环境 */
  /* PATH */
  sysPathList.insert(0, QDir::toNativeSeparators(jrePath));
  sysPathList.insert(0, QDir::toNativeSeparators(javaBin));

  /* classPath */
  QStringList classList;
  classList << "." << QDir::toNativeSeparators(javaClass)
            << QDir::toNativeSeparators(jreClass);
  /* JAVA_HOME */

  QProcessEnvironment env;
  env.clear();
  runProc.setProcessEnvironment(env);
  env = QProcessEnvironment::systemEnvironment();
  env.remove("JAVA_HOME");
  env.remove("CLASSPATH");
  env.remove("Path");
  env.insert("JAVA_HOME", QDir::toNativeSeparators(javaEnv));
  env.insert("CLASSPATH", classList.join(";"));
  env.insert("Path", sysPathList.join(";"));
  qputenv("JAVA_HOME", QDir::toNativeSeparators(javaEnv).toStdString().c_str());
  qputenv("CLASSPATH", classList.join(";").toStdString().c_str());
  qputenv("Path", sysPathList.join(";").toStdString().c_str());
  runProc.setProcessEnvironment(env);
}

void workProces::onReadData() {
  QByteArray da = runProc.readAllStandardOutput();
  emit ReadData(da);
}
void workProces::onReadError() {
  QByteArray da = runProc.readAllStandardError();
  emit ReadData(da);
}

void workProces::doMyWork() {
  if (bStart) {
    runProc.start(exeCmd, argList);
    runProc.waitForFinished(30000);
    emit finished();
    bStart = false;
  }
}
